//
//  UPMyOrderListViewController.m
//  Uang Pasti
//
//  Created by 李永彬 on 2025/8/22.
//

#import "UPMyLoanHistoryViewController.h"
#import "UPLoanHistoryCell.h"
#import "UPLoanStateView.h"

// 按钮标签枚举
typedef NS_ENUM(NSUInteger, LoanHistoryButtonType) {
    LoanHistoryButtonTypeAll = 0,
    LoanHistoryButtonTypeApplying,
    LoanHistoryButtonTypeRepayment,
    LoanHistoryButtonTypeFinish
};

@interface UPMyLoanHistoryViewController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UIScrollView *buttonScrollView;
@property (nonatomic, strong) UIStackView *buttonStackView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *buttonTitles;
@property (nonatomic, assign) LoanHistoryButtonType selectedButtonType;
@property (nonatomic, strong) HistoryLapidantModel *lapidantModel;

@property (nonatomic, strong) UPLoanStateView *stateView;
@property (nonatomic, strong) UIImageView *containerImageView;

@end

@implementation UPMyLoanHistoryViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor colorWithHexString:@"#8500FD"];
    self.title = LocalizableForKey(@"Loan History");
    
    // 初始化按钮标题
    self.buttonTitles = @[
        LocalizableForKey(@"All"),
        LocalizableForKey(@"Applying"),
        LocalizableForKey(@"Repayment"),
        LocalizableForKey(@"Finish")
    ];
    
    // 默认选中第一个按钮
    self.selectedButtonType = LoanHistoryButtonTypeAll;
    
    // 设置UI
    [self setupUI];
    [self setupConstraints];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.tableView.mj_header beginRefreshing];
}

- (void)setupUI {
    // 创建按钮滚动视图和堆栈视图
    self.buttonScrollView = [[UIScrollView alloc] init];
    self.buttonScrollView.showsHorizontalScrollIndicator = NO;
    self.buttonScrollView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.buttonScrollView];
    
    self.buttonStackView = [[UIStackView alloc] init];
    self.buttonStackView.axis = UILayoutConstraintAxisHorizontal;
    self.buttonStackView.alignment = UIStackViewAlignmentCenter;
    self.buttonStackView.distribution = UIStackViewDistributionEqualSpacing;
    self.buttonStackView.spacing = 9;
    [self.buttonScrollView addSubview:self.buttonStackView];
    
    // 创建按钮
    for (NSInteger i = 0; i < self.buttonTitles.count; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.tag = i;
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor colorWithHexString:@"#8500FD"] forState:UIControlStateSelected];
        UIImage *normalImage = [UIImage imageNamed:@"button_bg_style3_normal"];
        [button setBackgroundImage:normalImage forState:UIControlStateNormal];
        [button setBackgroundImage:[UIImage imageNamed:@"button_bg_style3_selected"] forState:UIControlStateSelected];
        if (i == self.selectedButtonType) {
            button.selected = YES;
        }
        
        [button setAttributedTitle:[TextOutlineUtil outlinedAttributedStringWithText:self.buttonTitles[i] font:[UIFont systemFontOfSize:14 weight:UIFontWeightBold] textColor:[[UIColor colorWithHexString:@"#000000"] colorWithAlphaComponent:0.3] outlineColor:[[UIColor colorWithHexString:@"#FFFFFF"] colorWithAlphaComponent:0.3] outlineWidth:2.0]
                          forState:UIControlStateNormal];
        
        [button setAttributedTitle:[TextOutlineUtil outlinedAttributedStringWithText:self.buttonTitles[i] font:[UIFont systemFontOfSize:14 weight:UIFontWeightBold] textColor:[UIColor colorWithHexString:@"#000000"] outlineColor:[UIColor colorWithHexString:@"#FFFFFF"] outlineWidth:2.0]
                          forState:UIControlStateSelected];
        
        [button addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];
        [self.buttonStackView addArrangedSubview:button];
        
        CGFloat width = 87;
        CGFloat ratio = 1.0;
        if (normalImage.size.width > 0 && normalImage.size.height > 0) {
            ratio = normalImage.size.width / normalImage.size.height;
        }
        CGFloat height = width / ratio;
        [button mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(width);
            make.height.mas_equalTo(height);
        }];
    }
    
    // 创建表格视图
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    __weak typeof(self) weakSelf = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf fetchData];
    }];
    
    if ([self.tableView.mj_header isKindOfClass:[MJRefreshNormalHeader class]]) {
        MJRefreshNormalHeader *header = (MJRefreshNormalHeader *)self.tableView.mj_header;
        [header setTitle:@"" forState:MJRefreshStateIdle];
        [header setTitle:@"" forState:MJRefreshStatePulling];
        [header setTitle:@"" forState:MJRefreshStateRefreshing];
        header.lastUpdatedTimeLabel.hidden = YES;
        header.stateLabel.hidden = YES;
    }
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.layer.cornerRadius = 12;
    self.tableView.clipsToBounds = YES;
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.showsVerticalScrollIndicator = NO;
    [self.tableView registerClass:[UPLoanHistoryCell class] forCellReuseIdentifier:@"Cell"];
    [self.view addSubview:self.tableView];
    
    [self.view addSubview:self.containerImageView];
    [self.view addSubview:self.stateView];
}

- (void)setupConstraints {
    // 按钮滚动视图约束
    [self.buttonScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.mas_topLayoutGuideBottom).offset(20);
        make.left.right.equalTo(self.view);
        make.height.equalTo(@50);
    }];
    
    // 按钮堆栈视图约束
    [self.buttonStackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.buttonScrollView).insets(UIEdgeInsetsMake(5, 16, 5, 16));
        make.height.equalTo(self.buttonScrollView).offset(-10);
    }];
    
    // 表格视图约束
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.buttonScrollView.mas_bottom).offset(20);
        make.left.equalTo(self.view).offset(16);
        make.right.equalTo(self.view).offset(-16);
        make.bottom.equalTo(self.view);
    }];
    
    // 容器图片约束
    UIImage *bgImage = [UIImage imageNamed:@"presonal_list_bg"];
    CGFloat bgAspectRatio = bgImage.size.width / bgImage.size.height;
    CGFloat bgWidth = kScreenWidth - 2 * 16;
    CGFloat bgHeight = bgWidth / bgAspectRatio;
    [self.containerImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.buttonStackView.mas_bottom).offset(60);
        make.centerX.equalTo(self.view);
        make.width.mas_equalTo(bgWidth);
        make.height.mas_equalTo(bgHeight);
    }];
    
    // 状态视图约束
    [self.stateView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.containerImageView);
        make.width.equalTo(self.containerImageView);
    }];
}

- (void)fetchData {
    __weak typeof(self) weakSelf = self;
    [SVProgressHUD show];
    LoanHistoryListType listType = LoanHistoryListTypeAll;
    switch (self.selectedButtonType) {
        case LoanHistoryButtonTypeAll:
            listType = LoanHistoryListTypeAll;
            break;
        case LoanHistoryButtonTypeApplying:
            listType = LoanHistoryListTypeApplying;
            break;
        case LoanHistoryButtonTypeRepayment:
            listType = LoanHistoryListTypeRepayment;
            break;
        case LoanHistoryButtonTypeFinish:
            listType = LoanHistoryListTypeFinish;
            break;
        default:
            break;
    }
    
    [UPStocksAPIManager fetchLoanHistoryListWithButtonType:listType completion:^(HistoryLapidantModel * _Nullable model, NSString * _Nullable msg) {
        [SVProgressHUD dismiss];
        [weakSelf.tableView.mj_header endRefreshing];
        
        if (model) {
            weakSelf.lapidantModel = model;
            [weakSelf.tableView reloadData];
            
            if (model.circumibility.count == 0) {
                // 显示空状态
                [weakSelf.stateView updateWithType:UPLoanStateViewTypeEmpty
                                              icon:@"error_icon"
                                             title:LocalizableForKey(@"There are currently no order records available")
                                       buttonTitle:LocalizableForKey(@"Go Apply")
                                        retryBlock:^{
                    [weakSelf retryButtonTapped];
                }];
                [weakSelf showStateView];
            } else {
                [weakSelf hideStateView];
                weakSelf.containerImageView.hidden = YES;
            }
        } else {
            // 显示错误状态
            [weakSelf.stateView updateWithType:UPLoanStateViewTypeError
                                          icon:@"error_icon"
                                         title:LocalizableForKey(@"no_network_history")
                                   buttonTitle:LocalizableForKey(@"Try it")
                                    retryBlock:^{
                [weakSelf retryButtonTapped];
            }];
            [weakSelf showStateView];
            
            if (msg) {
                [SVProgressHUD showInfoWithStatus:msg];
            }
        }
    }];
}

#pragma mark - State View Methods

- (void)showStateView {
    self.stateView.hidden = NO;
    self.tableView.hidden = YES;
    self.containerImageView.hidden = NO;
}

- (void)hideStateView {
    self.stateView.hidden = YES;
    self.tableView.hidden = NO;
    self.containerImageView.hidden = YES;
}

- (void)retryButtonTapped {
    if (self.stateView.loanStateViewType == UPLoanStateViewTypeEmpty) {
        [self.navigationController popToRootViewControllerAnimated:YES];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            UIViewController *rootVC = [UIApplication up_currentKeyWindow].rootViewController;
            if ([rootVC isKindOfClass:[UPTabBarViewController class]]) {
                UPTabBarViewController *mainVC = (UPTabBarViewController *)rootVC;
                [mainVC changeViewControllerToIndex:0];
            }
        });
    } else {
        [self hideStateView];
        [self.tableView.mj_header beginRefreshing];
    }
}

#pragma mark - Lazy Loading

- (UPLoanStateView *)stateView {
    if (!_stateView) {
        _stateView = [[UPLoanStateView alloc] init];
    }
    return _stateView;
}

- (UIImageView *)containerImageView {
    if (!_containerImageView) {
        _containerImageView = [[UIImageView alloc] init];
        _containerImageView.contentMode = UIViewContentModeScaleAspectFit;
        _containerImageView.image = [UIImage imageNamed:@"presonal_list_bg"];
        _containerImageView.userInteractionEnabled = YES;
        _containerImageView.hidden = YES;
    }
    return _containerImageView;
}

#pragma mark - Button Actions

- (void)buttonTapped:(UIButton *)sender {
    // 更新选中状态
    self.selectedButtonType = sender.tag;
    
    // 更新所有按钮状态
    for (UIButton *button in self.buttonStackView.arrangedSubviews) {
        if ([button isKindOfClass:[UIButton class]]) {
            button.selected = (button.tag == sender.tag);
        }
    }
    
    // 根据选中类型刷新表格数据
    [self loadDataForSelectedType];
}

- (void)loadDataForSelectedType {
    [self fetchData];
}

- (CGFloat)bgImageHeight {
    UIImage *image = [UIImage imageNamed:@"history_cell_bg"];
    CGFloat width = kScreenWidth - 2 * 16;
    CGFloat ratio = 1.0;
    if (image.size.width > 0 && image.size.height > 0) {
        ratio = image.size.width / image.size.height;
    }
    CGFloat height = width / ratio;
    return height;
}

-(void)pushToWebViewController: (NSString *)url {
    UPWebViewController *webVC = [[UPWebViewController alloc] init];
    webVC.urlString = url;
    webVC.isFollowOrder = NO;
    [[UIApplication up_currentViewController].navigationController pushViewController:webVC animated:YES];
}


#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.lapidantModel.circumibility.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UPLoanHistoryCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    HistoryCircumibilityModel *model = self.lapidantModel.circumibility[indexPath.section];
    cell.circumibilityModel = model;
    return cell;
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    HistoryCircumibilityModel *model = self.lapidantModel.circumibility[indexPath.section];
    if (model.sorptlocal != nil && model.sorptlocal.length > 0) {
        NSString *urlStr = model.sorptlocal ;
        if ([urlStr hasPrefix:@"http"] || [urlStr hasPrefix:@"https"]) {
            [self pushToWebViewController:urlStr];
        } else {
            [[UPSchemeManager shared] parser:urlStr];
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [self bgImageHeight] + 22;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 15;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] init];
    return view;
}

@end
